package com.cai.dao.impl;

import com.cai.dao.MsgDao;
import com.cai.entity.Msg;
import com.cai.util.C3p0Util;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author RuoLi
 * 消息实现类
 */
public class MsgDaoImpl implements MsgDao {

    static QueryRunner runner = new QueryRunner(C3p0Util.getDataSource());

    String userSendTime = null;
    String userReturnTime = null;
    String userSendDate = null;
    String userReturnDate = null;

    @Override
    public int sendMsg(String msg, String sendUserName, String returnUserName) {
        LocalDateTime dateTime = LocalDateTime.now();
        userSendTime = dateTime.toLocalTime().toString().substring(0, 5);
        userSendDate = dateTime.toLocalDate().toString();
        String sql = "INSERT INTO msg(msg_sendDate,msg_sendTime,msg_sendText,msg_sendUser,msg_returnUser) VALUES (?,?,?,?,?)";
        Object[] args = {userSendDate, userSendTime, msg, sendUserName, returnUserName};
        return msg(sql, args);
    }

    @Override
    public int returnMsg(String msg, String msgSendDate, String msgSendTime, String sendUserName, String returnUserName) {
        LocalDateTime dateTime = LocalDateTime.now();
        //时间取前五位字符 12:20
        userReturnTime = dateTime.toLocalTime().toString().substring(0, 5);
        userReturnDate = dateTime.toLocalDate().toString();
        String sql = "UPDATE msg SET msg_returnText= ? ,msg_returnDate= ? , msg_returnTime= ? WHERE msg_sendDate=? AND msg_sendTime= ? AND msg_sendUser= ? AND msg_returnUser= ?";
        Object[] args = {msg, userReturnDate, userReturnTime, msgSendDate, msgSendTime, sendUserName, returnUserName};
        return msg(sql, args);
    }

    @Override
    public List<Msg> allMsg() {
        String sql = "select * from msg";
        try {
            return  runner.query(sql, new BeanListHandler<>(Msg.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 私有消息方法
     *
     * @param sql    sql语句
     * @param params sql参数
     * @return 1 成功
     */
    private int msg(String sql, Object[] params) {
        try {
            int count = runner.update(sql, params);
            if (count != 0) {
                return 1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

}
